package indi.mozping.container.bits;

/**
 * @author by mozping
 * @Classname Permission
 * @Description 使用位运算来设计权限
 * @Date 2019/3/5 14:38
 */
public class Permission {

    //权限标志位
    int flag;
    //新增权限
    public static final int ADD_PERMISSION = 1 << 0;
    //删除权限
    public static final int DEL_PERMISSION = 1 << 1;
    //修改权限
    public static final int MODIFY_PERMISSION = 1 << 2;
    //查询权限
    public static final int QUERY_PERMISSION = 1 << 3;

    //设置权限
    public void setPer(int per) {
        flag = per;
    }

    //增加权限，按位或运算
    public void addPer(int per) {
        flag = flag | per;
    }

    //删除权限，与取非之后的数按位与
    public void delPer(int per) {
        flag = flag & ~per;
    }

    //获取权限
    public int getPer() {
        return flag;
    }

    //判断是否有指定权限
    public boolean isAllowPer(int per) {
        return (flag & per) == per;
    }

    public static void main(String[] args) {
        Permission permission = new Permission();
        permission.setPer(15);
        System.out.println("add permission:" + permission.isAllowPer(ADD_PERMISSION));
        System.out.println("del permission:" + permission.isAllowPer(DEL_PERMISSION));
        System.out.println("modify permission:" + permission.isAllowPer(MODIFY_PERMISSION));
        System.out.println("query permission:" + permission.isAllowPer(QUERY_PERMISSION));
        System.out.println("---------------------------");
        permission.delPer(ADD_PERMISSION | DEL_PERMISSION);
        System.out.println("add permission:" + permission.isAllowPer(ADD_PERMISSION));
        System.out.println("del permission:" + permission.isAllowPer(DEL_PERMISSION));
        System.out.println("modify permission:" + permission.isAllowPer(MODIFY_PERMISSION));
        System.out.println("query permission:" + permission.isAllowPer(QUERY_PERMISSION));
        permission.addPer(ADD_PERMISSION);
        System.out.println("---------------------------");
        System.out.println("add permission:" + permission.isAllowPer(ADD_PERMISSION));
        System.out.println("del permission:" + permission.isAllowPer(DEL_PERMISSION));
        System.out.println("modify permission:" + permission.isAllowPer(MODIFY_PERMISSION));
        System.out.println("query permission:" + permission.isAllowPer(QUERY_PERMISSION));
        System.out.println("---------------------------");
        System.out.println(permission.isAllowPer(QUERY_PERMISSION));
    }
}
